# coding=utf-8
# !/usr/bin/python
import requests
import json


# 请求 有道翻译 首页
def get_translate_content(keyword=None):
    url = 'https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
    form_data = {
        "i": keyword,
        "from": "AUTO",
        "to": "AUTO",
        "smartresult": "dict",
        "client": "fanyideskweb",
        "salt": "16373081252851",
        "sign": "854e12caac146c01ee35ab27e25739f7",
        "lts": "1637308125285",
        "bv": "5249ad31eb31536d2c0c60c918ac1259",
        "doctype": "json",
        "version": "2.1",
        "keyfrom": "fanyi.web",
        "action": "FY_BY_CLICKBUTTION"
    }
    pre_header = {
        "Accept": "application/json,text/javascript,*/*;q=0.01",
        "Accept-Encoding": "gzip,deflate,br",
        "Accept-Language": "zh,en-US;q=0.9,en;q=0.8,zh-CN;q=0.7,ja;q=0.6",
        "Connection": "keep-alive",
        "Content-Length": "268",
        "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        "Cookie": "OUTFOX_SEARCH_USER_ID=220398662@10.169.0.102; JSESSIONID=aaa0Qi2AJXKXFdc4Jc30x; OUTFOX_SEARCH_USER_ID_NCOO=450767471.01571196; ___rl__test__cookies=1637308125283",
        "Host": "fanyi.youdao.com",
        "Origin": "https://fanyi.youdao.com",
        "Referer": "https://fanyi.youdao.com/",
        "sec-ch-ua": "'NotA;Brand';v='99','Chromium';v='96','GoogleChrome';v='96'",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "macOS",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "same-origin",
        "User-Agent": "Mozilla/5.0(Macintosh;IntelMacOSX10_14_6)AppleWebKit/537.36(KHTML,likeGecko)Chrome/96.0.4664.45Safari/537.36",
        "X-Requested-With": "XMLHttpRequest"
    }
    resp = requests.post(url, data=form_data, headers=pre_header)
    res_json = json.loads(resp.text)

    origin_text = res_json['translateResult'][0][0]['src']
    translate_text = res_json['translateResult'][0][0]['tgt']

    print("原文:{0},翻译:{1}".format(origin_text, translate_text))


if __name__ == '__main__':
    get_translate_content('你好呀')
